var mgeMenu = {
    tableid: "table1",
    treetable: null,
    iconlay: null,
    layerindex: null
};
/**
 * 初始化表格的列
 */
mgeMenu.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: '菜单ID', field: 'id', visible: false, align: 'center', valign: 'middle', width: '180px'},
        {title: '菜单名称', field: 'name', align: 'center', valign: 'middle', sortable: true, width: '280px'},
        {
            title: '图标',
            field: 'icon',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: '80px',
            formatter: function (t, item, index) {
                return item.icon == null ? '' : '<i class="' + item.icon + ' fa-lg"></i>';
            }
        },
        {
            title: '类型',
            field: 'type',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: '100px',
            formatter: function (t, item, index) {
                if (item.type === 0) {
                    return '<span class="label label-primary">目录</span>';
                }
                if (item.type === 1) {
                    return '<span class="label label-success">菜单</span>';
                }
                if (item.type === 2) {
                    return '<span class="label label-warning">按钮</span>';
                }
            }
        },
        {
            title: '排序号', field: 'orderNum', align: 'center', valign: 'middle', sortable: true, width: '100px'
        },
        {
            title: '菜单URL', field: 'url', align: 'center', valign: 'middle', sortable: true, width: '160px'
        },
        {
            title: '授权标识',
            field: 'perms',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: '50px',
            formatter: function (v, r) {
                if (v != null) {
                    if (v.length > 10) {
                        return "<div title='" + v + "'>" + v.substring(0, 7) + "..." + "</div>";
                    }
                }
                return v;
            }
        }]
    return columns;
};
mgeMenu.openIcon = function () {
    var hei = $(window).height() - 20;
    var wi = $(window).width() - 20;
    mgeMenu.iconlay = layer.open({
        type: 2,
        title: "图标选择",
        shadeClose: true,
        shade: false,
        maxmin: true,
        area: [wi + "px", hei + "px"],
        content: ctx + "/mge/adx/sys/selectIcons"
    });
}
mgeMenu.setIcon = function (v) {
    $("#icon").val(v);
    layer.close(mgeMenu.iconlay);
}
mgeMenu.clearInputs = function () {
    var ipts = $("#form_opt").find("[data-type='rep']");
    if (ipts.length > 0) {
        ipts.each(function (i, v) {
            $(v).val("");
            var er = $(v).next();
            if (er.length > 0 && $(er).prop("nodeName").toLowerCase() == "em") {
                er.remove();
                var hs = $(v).parent().parent();
                hs.removeClass("has-success");
                hs.removeClass("has-error");
            }
        });
    }
    $("#orderNum").val("100");
    $("#id").val("");
    $("#parentId_chosen").find("span").html("");
}
mgeMenu.openDlg = function (title) {
    var hei = $(window).height() - 20;
    var wi = $(window).width() - 20;
    mgeMenu.layerindex = layer.open({
        type: "1",
        title: title ? title : "添加",
        area: [(wi > 650 ? 650 : wi) + 'px', (hei > 500 ? 500 : hei) + 'px'],
        shade: 0.4,
        maxmin: true,
        btn: ["确定", "取消"],
        content: $("#menuropt"),
        scrollbar: false,
        success: function (layero, index) {

        },
        yes: function (index) {
            $("#form_opt").submit();
            //mgeRole.postAjaxFrom();
            mgeMenu.layerindex = index;
        }, btn2: function (index) {
            mgeMenu.clearInputs();
        }, cancel: function () {
            mgeMenu.clearInputs();
        }
    });
};
/**
 * 检查是否选中
 */
mgeMenu.check = function () {
    var selected = $('#' + this.tableid).bootstrapTreeTable('getSelections');
    if (selected.length == 0) {
        //Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        // Menu.seItem = selected[0];
        return true;
    }
};
mgeMenu.addOnClick = function () {
    $("#add").on("click", function (e) {
        e.preventDefault();
        mgeMenu.openDlg();
    });
}
mgeMenu.updateOnClick = function () {
    $("#update").on('click', function (e) {
        e.preventDefault();
        var row = mgeMenu.treetable.getSelections();
        if (row == null) {
            layer.alert("请选中您要修改数据！");
            return false;
        }
        mgeMenu.openDlg("修改");
        mgeMenu.getByMenuid(row.id);
    });
}

mgeMenu.delOnClick = function () {
    $("#del").on('click', function (e) {
        e.preventDefault();
        var row = mgeMenu.treetable.getSelections();
        if (row == null) {
            layer.alert("请选中您要修改数据！");
            return false;
        }
        var lay = layer.load({shade: [0.1]});
        $.ajax({
            url: ctx + "/mge/adx/delMenu",
            data: {id: row.id},
            type: "post",
            dataType: "json",
            success: function (data, sta) {
                layer.close(lay);
                if (data != null && data.code == '200') {
                    cmm.layerMessge("删除成功");
                    if (row.tr) {
                        row.tr.remove();
                    }
                }
            },
            error: function (sta) {
                layer.close(lay);
                layer.alert("请求失败，请重试或检查网络！");
            }
        })
    });
}
mgeMenu.search = function () {
    mgeMenu.treetable.refresh({query: cmm.serializeObject($("#form_search"))});
}
mgeMenu.resHeigth = function () {
    var he = $(window).height() - 10;
    return he;
}
mgeMenu.postAjaxFrom = function () {
    $("#form_opt").validate({
        rules: {
            name: {
                "required": true, maxlength: 20, textChvail: true
            },
            url: {"required": true, maxlength: 400, textEnvail: true},
            pid: {"required": true},
            perms: {"required": false, maxlength: 450, textEnvail: true}
        }, messages: {
            name: {"required": "请输入模块名称", maxlength: "最大20字符"},
            url: {"required": "目录请输入#", maxlength: "最大400字符"},
            pid: {"required": "请选择上级模块"},
            perms: {maxlength: "最大450字符"}
        }, success: function (label) {

        }, onkeyup: function (element) {
            $(element).valid();
        }, onfocusout: false, errorElement: "em", errorPlacement: function (error, element) {
            $(error).css({"color": "red", "font-size": "15px"});
            $(element).parent().append(error);
        }, highlight: function (element, errorClass, validClass) {
            var md = $(element).parent().parent().addClass("has-error").removeClass("has-success");
        }, unhighlight: function (element, errorClass, validClass) {
            $(element).parent().parent().addClass("has-success").removeClass("has-error");
        }, submitHandler: function () {
            if (!$("#form_opt").valid()) {
                return false;
            }
            if ($("#pid").val() == "") {
                $("#pid").parent().append($("<em>请选择上级模块</em>").css({"color": "red", "font-size": "15px"}));
                $("#pid").parent().parent().addClass("has-error").removeClass("has-success");
            }
            mgeMenu.ajax();
            return false;
        }
    });
}
mgeMenu.getByMenuid = function (id) {
    var lay = layer.load({shade: [0.1]});
    $.ajax({
        url: ctx + "/mge/adx/getBymenuid",
        data: {id: id},
        dataType: "json",
        type: 'post',
        success: function (d, s) {
            layer.close(lay);
            if (d.code == '200') {
                cmm.fromData(d.data);
                $("#spinner1").spinner({value: d.data.orderNum});
                $("#type").val(d.data.type);
                $("#type").trigger("chosen:updated");
                var sapn = $("#parentId_chosen").find("span");
                var str = "";
                if (d.data.pid == "0") {
                    str = "功能目录";
                } else {
                    var ztree = $.fn.zTree.getZTreeObj("funtree1");
                    var nodes = ztree.getNodes();
                    if (nodes.length > 0) {
                        str = mgeMenu.getNodesName(nodes[0], d.data.pid);
                    }
                }
                sapn.html(str);
                $("#form_opt").valid();
            } else {
                layer.alert(d.message);
            }
        }, error: function (sta) {
            layer.close(lay);
            layer.alert("请求失败，请重试或检查网络！");
        }
    });
}
mgeMenu.treeRefresh = function (v) {
    var ztree = $.fn.zTree.getZTreeObj(v);
    ztree.reAsyncChildNodes(ztree.getNodeByParam('id', $("#pid").val(), null), "refresh", true);
}
mgeMenu.ajax = function () {
    var lay = layer.load(0, {shade: [0.1]});
    if ($("#id").val() == "") {
        $.ajax({
            url: ctx + "/mge/adx/addMenu",
            data: $("#form_opt").formSerialize(),
            type: "post",
            dataType: "json",
            success: function (data, stat, jqh) {
                layer.close(lay);
                layer.close(mgeMenu.layerindex);
                if (data.code == '200') {
                    mgeMenu.treetable.refresh();
                    mgeMenu.treeRefresh("funtree1");
                    mgeMenu.clearInputs();
                    cmm.layerMessge("添加成功！");
                } else {
                    layer.alert(data.message);
                }
            },
            error: function (d) {
                layer.close(lay);
                layer.alert("请求失败请重试或检查网络！");
            }
        });
    } else {
        $.ajax({
            url: ctx + "/mge/adx/updateMenu",
            data: $("#form_opt").formSerialize(),
            type: "post",
            dataType: "json",
            success: function (data, stat, jqh) {
                layer.close(lay);
                layer.close(mgeMenu.layerindex);
                if (data.code == '200') {
                    mgeMenu.treeRefresh("funtree1");
                    mgeMenu.treetable.refresh();
                    mgeMenu.clearInputs();
                    cmm.layerMessge("修改成功！");
                } else {
                    layer.alert(data.message);
                }
            },
            error: function (d) {
                layer.close(lay);
                layer.alert("请求失败请重试或检查网络！");
            }
        });
    }
}
mgeMenu.select = function () {
    var s = $(".bs-select").chosen({width: '100%', disable_search: true});
    //show.bs.select
    //shown.bs.select 当下拉菜单对用户可见出发
    //loaded.bs.select 初始化后触发
    //hide.bs.select
    $(".bs-select").on("change", function (e, params) {

    });
    return s;
}

mgeMenu.comboxTree = function () {
    $("#parentId_chosen").on('click', function () {
        var cityObj = $(this);
        var cityOffset = $(this).offset();
        $("#menuContent").css({
            left: cityOffset.left + "px", top: cityOffset.top + cityObj.outerHeight() + "px"
        }).slideDown("fast");
        $("#menuContent").width($(this).width());
        $("body").bind("mousedown", onBodyDown);
    });
}
mgeMenu.getNodesName = function (nodes, id) {
    if (nodes && nodes.children && nodes.children.length > 0) {
        for (var i = 0; i < nodes.children.length; i++) {
            if (nodes.children[i].id == id) {
                return nodes.children[i].name;
            } else {
                var ss = mgeMenu.getNodesName(nodes.children[i], id);
                if (ss != "") {
                    return ss;
                }
            }
        }
        return "";
    } else {
        return "";
    }
}
mgeMenu.getTree = function () {
    $.fn.zTree.init($("#funtree1"), {
        view: {
            dblClickExpand: false
        }, async: {
            enable: true, url: ctx + "/mge/adx/treefunc?type=menu", dataFilter: ajaDataFilter, autoParam: ["id"]
        }, data: {}, callback: {
            beforeClick: function () {
                return true;
            }, onClick: function (e, treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("funtree1"), nodes = zTree
                    .getSelectedNodes();
                if (nodes.length > 0) {
                    var cityObj = $("#parentId_chosen").find("span");
                    $(cityObj).html(nodes[0].name);
                    $("#pid").val(nodes[0].id);
                    $("#pid").parent().parent().addClass("has-success").removeClass("has-error");
                    $("#pid").next().html("");
                }

            }
        }
    });
}

function ajaDataFilter(treeid, parentNode, respsnseData) {
    if (respsnseData != null && respsnseData.code == "200") {
        if (parentNode == null) {
            var data = [
                {
                    id: 0, name: "功能目录", children: respsnseData.data
                }
            ];
            return data;
        } else {
            return respsnseData.data;
        }
    }
    return [
        {}
    ];
}

function hideMenu() {
    $("#menuContent").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
}

function onBodyDown(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target)
        .parents("#menuContent").length > 0)) {
        hideMenu();
    }
}

$(function () {
    var defaultColunms = mgeMenu.initColumn();
    var table = new BSTreeTable(mgeMenu.tableid, ctx + "/mge/adx/listMenus?rad=" + new Date().getTime(), defaultColunms);
    table.setExpandColumn(2);
    table.setIdField("id");
    table.setCodeField("id");
    table.setParentCodeField("pid");
    table.setExpandAll(false);
    table.setOnLoadSuccess(function (data) {
        if (data.code == '200') {
            return data.rows;
        }
        return [];
    });
    table.init();
    mgeMenu.addOnClick();
    mgeMenu.updateOnClick();
    mgeMenu.delOnClick();
    mgeMenu.postAjaxFrom();
    mgeMenu.treetable = table;
    mgeMenu.select();
    mgeMenu.getTree();
    mgeMenu.comboxTree();
    $("#spinner1").spinner({value: 100, step: 1, min: 1, max: 9999});
    $("#orderNum").blur(function () {
        if ($(this).val() == "") {
            $(this).val(100);
        }
    });
    $("#icon").on("click", function () {
        mgeMenu.openIcon();
    });
});
